package com.peaker.advertisingpro.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.peaker.advertisingpro.R
import com.peaker.advertisingpro.base.BaseActivity
import com.peaker.advertisingpro.bean.*
import com.peaker.advertisingpro.db.AppDatabase
import com.peaker.advertisingpro.fragment.ScrollFragment
import com.peaker.advertisingpro.listener.OnDownloadListener
import com.peaker.advertisingpro.listener.RequestListener
import com.peaker.advertisingpro.tcp.RequestCallback
import com.peaker.advertisingpro.tcp.ResponseCallback
import com.peaker.advertisingpro.tcp.TCPClient
import com.peaker.advertisingpro.utils.*
import com.peaker.advertisingpro.view.MsgDialog
import com.peaker.advertisingpro.view.PwdDialog
import com.peaker.advertisingpro.view.SetDialog
import kotlinx.android.synthetic.main.activity_scroll.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
import kotlin.system.exitProcess


/**
 * 节目播放界面
 */
class ScrollActivity : BaseActivity() {
    private var heartJson = Gson().toJson(HeartBean())
    var arrayList = ArrayList<Fragment>()
    var playTimes = ArrayList<Int>()//每个场景播放的时间
    var idList = ArrayList<String>()//每个场景的id
    lateinit var handler: Handler
    lateinit var parameter: ProgramBean
    lateinit var dialog:MsgDialog
//    lateinit var parameter: ProgramBean

    companion object instance {
        lateinit var scrollAsc: Context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scroll)
//        AppDatabase.instance.programUrlDao().deletAll()
//        AppDatabase.instance.programJsonDao().deletAll()
        scrollAsc = this
        handler = Handler()
         dialog = MsgDialog(this@ScrollActivity,"设备还未激活请先激活")
       
        SPUtil.putSP(Common.ISCONNECT, "否")
        val dir = File(Common.DIRADDRESS)
        if (!dir.exists()) {
            dir.mkdirs()
        }

//        startActivity(Intent(this, TestActivity::class.java))
        var sp = SPUtil.getSP(Common.ANGLE, "0")
        setScreenonChange(sp!!)

        viewPage.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = arrayList.size
            override fun createFragment(position: Int): Fragment = arrayList[position]
            override fun getItemId(position: Int): Long {
                return arrayList[position].hashCode().toLong()
            }


        }

        viewPage.isUserInputEnabled = false
        viewPage.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        viewPage.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                var index = position + 1
                if (arrayList.size == (position + 1)) {
                    //最后一个 重新解析数据库数据
                    index = 0
                    fomatJson()

                }
                try {
                    Common.programId=idList.get(position)//当前节目的id
                    if (arrayList.isEmpty().not()) {
                        setHandlerDelay(
                            index,
                            TimeUtil.getLongMs(playTimes[position])
                        )
                    }
                } catch (e: Exception) {
                    Log.d("错误数据", "viewpage切换的时候报错...")
                }

            }
        })
        viewPage.currentItem = 0
        img.setOnClickListener {
            (viewPage.adapter as FragmentStateAdapter).notifyDataSetChanged()
        }

        fomatJson()
        //插播内容
        interPlayText()

        //添加删除文件的任务
        addTask()
        //添加设置音量计划
        setVolumePlan()
    }

    private fun addTask() {
        //创建定时任务清理不用的资源文件
//        （秒、分、时、日、月、周）
        SchedulerUtils.addScheduler("0 10 23 * * *") { delFile() }
        SchedulerUtils.addScheduler("0 53 18 * * *") { reportPlays() }

    }

    /**
     * 设置屏幕旋转
     */

     fun setScreenonChange(a:String) {
        var flag = SPUtil.getSP(Common.ANGLE, "0")

        when(a){
            "0","180"->{
                if (flag == "0" || flag == "180") {
                    root_view.rotation = a.toFloat()
                    root_view.requestLayout()
                    SPUtil.putSP(Common.ANGLE, a)
                } else {
                    setAngle(a)
                }
            }
            "90","270"->{
                if (flag == "90" || flag == "270") {
                    root_view.rotation = a.toFloat()
                    root_view.requestLayout()
                    SPUtil.putSP(Common.ANGLE, a)
                } else {
                    setAngle(a)
                }

            }
        }





    }

   fun  setAngle(a: String){
        SPUtil.putSP(Common.ANGLE, a)
        var angle = a.toInt()

        val w: Int = root_view.width
        val h: Int = root_view.height
        root_view.rotation = angle.toFloat()
        if (angle % 180 == 90) {
            root_view.translationX = ((w - h) / 2).toFloat()
            root_view.translationY = ((h - w) / 2).toFloat()

        } else {
            root_view.translationX = 0f
            root_view.translationY = 0f
        }
        val lp = root_view.layoutParams
        lp.height = w
        lp.width = h
        root_view.requestLayout()
    }

    /**
     * 解析节目
     */
    fun fomatJson() {
        var endDate = SPUtil.getSP(Common.AUTHTIMEEND)
        var startDate = SPUtil.getSP(Common.AUTHTIMESTART)
        if ((endDate.isNullOrEmpty() or startDate.isNullOrEmpty()).not()) {
            //判断是否到期
            var expire = DateUtils.isEffectiveDate(
                Date(),
                DateUtils.getDateByStr(startDate!!),
                DateUtils.getDateByStr(endDate!!)
            )
            if (!expire) {
                SendMsg("5", NullData())
            }
        }

        //todo  将所有数据解析 加载到list 中,当播放完重新解析(从数据库里面解析判断是都可以播放)
        //所有节目
        var programUrlBeanList = AppDatabase.instance.programUrlDao().getProgramUrlBean()
        if (programUrlBeanList.size == 0) return
        //目标文件 arrayList
        arrayList.clear()
        playTimes.clear()
        idList.clear()
        programUrlBeanList.forEach constituting@{ bean ->
            var jsonList = ArrayList<String>()
            //是否满足时间要求
            var isplay = verifyTimeFun(bean)
            //满足时间播放次数加一
            if (isplay) {
                DBUtils.addPlayNum(bean.programId, "2")

                if (bean.type == "1") {//列表
                    var jsons = AppDatabase.instance.programJsonDao().getJsonByPId(bean.programId)
                    jsons.forEach { b ->
                        b.json?.let {
                            jsonList.add(it)
                        }
                    }
                } else {
                    jsonList.add(bean.json!!)
                }
                jsonList.forEach {
                    val type = object : TypeToken<ProgramBean>() {}.type
                    parameter = Gson().fromJson<ProgramBean>(it, type)

                    if (parameter.scenesCount == 0) {
                        return@constituting
                    }
                    for (index in 0 until parameter.scenesCount!!) {
                        parameter.scenes?.get(index)
                            ?.let {
                                arrayList.add(ScrollFragment.newInstance(it, "${bean.programId}"))
                                playTimes.add(it.duration!!)
                                idList.add(parameter.id!!)
                            }
                    }
                    //解析成功添加播放次数
                    parameter.resources?.let {
                        it.forEach { res ->
                            res.resId?.let { id ->
                                DBUtils.addPlayNum(id, "1")

                            }
                        }
                    }

                }


            }


        }
        GlobalScope.launch(Dispatchers.Main) {
            (viewPage.adapter as FragmentStateAdapter).notifyDataSetChanged()
            Log.d("数据当前线程", Thread.currentThread().name)
        }

    }

    /**
     * 验证播放时间
     * @param bean ProgramUrlBean
     */
    private fun verifyTimeFun(bean: ProgramUrlBean): Boolean {
        var isPlay = DateUtils.isEffectiveDate(
            Date(),
            DateUtils.getDateByStr(bean.startDate!!),
            DateUtils.getDateByStr(bean.endDate!!)
        )
        if (bean.plan == "2") {//时段模式
            isPlay = bean.weeks?.contains(TimeUtil.dayForWeek()) == true
            if (isPlay) {
                bean.times?.let {
                    isPlay = false
                    var objByJson = JsonObjectUtils.getObjByJson<List<Time>>(it)
                    objByJson.forEach { time ->
                        var isTimePlay = DateUtils.isEffectiveDate(
                            Date(),
                            DateUtils.getDateByHm(time.onTime!!),
                            DateUtils.getDateByHm(time.offTime!!)
                        )
                        if (isTimePlay) {
                            isPlay = true
                        }
                    }
                }
            }
        }
        return isPlay
    }

    private fun setHandlerDelay(index: Int, time: Long) {
        handler.postDelayed(Runnable {
            //            viewPage.currentItem = index
            if (index == 0) {
                viewPage.setCurrentItem(index, false)
            } else {
                viewPage.currentItem = index
            }
        }, time)


    }


    /**
     * 跳转场景
     */
    //todo 需修改 因为 parameter 是多个json
    fun jumpScenes(id: String) {

    }

    /**
     * 跳转动态元素
     */
    //todo 需修改 因为 parameter 是多个json
    fun jumpScenesE(id: String, linkDynamic: LinkDynamic) {


    }


    /**
     * 跳转app
     */
    fun jumpApp(appname: String) {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        val cn = ComponentName(packageName, appname)
        intent.component = cn
        startActivity(intent)
    }

    /**
     * 处理返回键
     */
    private var mExitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_TAB) {

            if (TextUtils.isEmpty(SPUtil.getSP(Common.PWD)).not()) {
                var pwdDialog = PwdDialog(this)
                pwdDialog.show()
                pwdDialog.onPwdSucced = {
                    if (it == 0) {//密码成功
                        SetDialog(this).show()
                    } else {
                        ToastUtils.s("密码错误")
                    }
                }
            } else {//无密码
                SetDialog(this).show()
            }

        }


        Log.d("按鍵拦截: ", "keyCode $keyCode ${Gson().toJson(event)}")

        if (keyCode == KeyEvent.KEYCODE_BACK) { // 判断菜单是否关闭
            // 判断两次点击的时间间隔（默认设置为2秒）
            if (System.currentTimeMillis() - mExitTime > 2000) {
                ToastUtils.s("再按一次退出程序")
                mExitTime = System.currentTimeMillis()
            } else {

                if (!TextUtils.isEmpty(SPUtil.getSP(Common.PWD))) {
                    var pwdDialog = PwdDialog(this)
                    pwdDialog.show()
                    pwdDialog.onPwdSucced = {
                        if (it == 0) {
                            this.finish()
                            exitProcess(0)
                        } else {
                            ToastUtils.s("密码错误")
                        }
                    }
                } else {
                    this.finish()
//                    exitProcess(0)
                }

            }

            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    /**
     * tcp连接
     */
    fun tcpConnect(byteArray: ByteArray) {
        var ip = SPUtil.getSP(Common.IP, Common.ip)
        if (ip.isNullOrEmpty()) {
            return
        }
        var iport = SPUtil.getSP(Common.MSG_PORT, Common.msg_port)
        TCPClient.build()
            .server(ip, iport!!.toInt())
            .breath(MsgUtils.stringToByte(heartJson), 8 * 1000)
            .connTimeout(10 * 1000)
            .request(byteArray, 10000, object : RequestCallback() {
                override fun onConnect() {
                    //连接成功
                    SPUtil.putSP(Common.ISCONNECT, "是")

//                    ToastUtils.s("连接成功")
                }

                override fun onFail(throwable: Throwable?) {
//                    ToastUtils.s("连接失败")
                    SPUtil.putSP(Common.ISCONNECT, "否")
                    SPUtil.putSP(Common.LOGIN_STATE, "未登录")
                    handler.postDelayed(Runnable {
                        var gson = Gson()
                        var loginJson = gson.toJson(ResultJson(gson.toJson(loginBean())))
                        tcpConnect(MsgUtils.stringToByte(loginJson))
                    }, 15_000)
                }

                override fun onTimeout() {

                }
            }, object : ResponseCallback() {
                override fun onRec(str: String) {

                    Log.d("接收数据解密前 : ", str)
                    val type1 = object : TypeToken<ResultJson>() {}.type
                    val jsonData = Gson().fromJson<ResultJson>(str, type1)
                    var json = jsonData.data!!
                    if (jsonData.encrypt == 1) {
                        json = AESCBCUtil.decrypt(
                            jsonData.data,
                            SPUtil.getSP(Common.KEY, "666823353237344A40662A7236355223")
                        )
                    }
                    Log.d("接收数据解密后 : ", json)
                    val type = object : TypeToken<ResultBean<NullData>>() {}.type
                    val data = Gson().fromJson<ResultBean<NullData>>(json, type)

                    if (data.type!!.toInt() >= 1000) {
                        data.code = "1"
                    }
                    if (data.code == "0" && data.type == "1") {//登录未成功调用注册
                        senRegistMsg()
                    }

                    if (data.code == "1") { //请求成功
                        when (data.type) {
                            "1" -> {//登录
                                if (Common.LOGINGFLAG == 1) {
                                    ToastUtils.s("登录成功")
                                }
                                SPUtil.putSP(Common.LOGIN_STATE, "已登录")
                                SPUtil.putSP(Common.MOUDLE, "联机模式")
                                Common.LOGINGFLAG = 0
                                if (LoginActivity.isClickLogin) {
                                    LoginActivity.loginAc?.let {
                                        if (it.isDestroyed.not()) {
                                            it.finish()
                                        }
                                    }
                                }
//                                ToastUtils.s("登录成功")
                                val type = object : TypeToken<ResultBean<loginResult>>() {}.type
                                val data = Gson().fromJson<ResultBean<loginResult>>(json, type)
                                SPUtil.putSP(Common.KEY, data.data.aesPassword)
                                if (TextUtils.isEmpty(data.data.register)
                                        .not() && data.data.register == "1"
                                ) {
                                    setLoginSet(data.data)
                                } else {//未注册

                                    senRegistMsg()
                                }
                            }
                            "2" -> {//注册成功
                                login()
                            }
                            "4" -> {// 成功
                                //清空表
                                AppDatabase.instance.resPlayNumDao().deletAll()
                            }
                            "5" -> {//设备过期  响应
                                returnFun("1", data.type!!)
                            }
                            "1001" -> {//设置
                                returnFun("1", data.type!!)
                                val type = object : TypeToken<ResultBean<SetData>>() {}.type
                                val data = Gson().fromJson<ResultBean<SetData>>(json, type)
                                setDevices(data.data)

                            }
                            "1002" -> {//更新
                                val type = object : TypeToken<ResultBean<UpDataBean>>() {}.type
                                val data = Gson().fromJson<ResultBean<UpDataBean>>(json, type)

                                UpDatafun(data.data)

                            }
                            "1003" -> {//节目更新
                                if(SPUtil.getSP(Common.AUTH,"无")=="无"){
                                    dialog.show()
                                }
                                    val type = object : TypeToken<ResultBean<ProgramUrlBean>>() {}.type
                                    val data = Gson().fromJson<ResultBean<ProgramUrlBean>>(json, type)
                                    dowmProgramFun(data.data)
                                

                            }
                            "1004" -> {//TODO 开关机设置
                                AppDatabase.instance.switchDao().deletAll()
                                val type =
                                    object : TypeToken<ResultBean<SwitchMachineSetBean>>() {}.type
                                val data =
                                    Gson().fromJson<ResultBean<SwitchMachineSetBean>>(json, type)
                                var bootbean = data.data

                                bootbean.bootTime?.highest?.let {
                                    AppDatabase.instance.switchDao().insert("highest",it)
                                    // todo 跨日期
                                }
                                bootbean.bootTime?.specialTime?.let {
                                    AppDatabase.instance.switchDao().insert("specialTime",it)

                                }
                                bootbean.bootTime?.week?.let {
                                    AppDatabase.instance.switchDao().insert("week",it)
                                }
                            }
                            "1005" -> {//音量设置
                                val type = object : TypeToken<ResultBean<VolumeSetBean>>() {}.type
                                val data = Gson().fromJson<ResultBean<VolumeSetBean>>(json, type)

                                data.data.volumeSet?.let {
                                    AppDatabase.instance.volumeDao().deletAll()
                                    AppDatabase.instance.volumeDao().insertAll(data.data.volumeSet)
                                    setVolumePlan()
                                }
                            }
                            "1006" -> {//上传截图文件 UPImgBean
                                val type = object : TypeToken<ResultBean<UPImgBean>>() {}.type
                                val data = Gson().fromJson<ResultBean<UPImgBean>>(json, type)
                                data.data.id?.let {
                                    upScreenshotsImg(it)
                                }
                            }
                            "1007" -> {//节目下线
                                val type = object : TypeToken<ResultBean<OfflineBean>>() {}.type
                                val data = Gson().fromJson<ResultBean<OfflineBean>>(json, type)
                                var jsonObject = data.data
                                if (jsonObject.status == "1" && jsonObject.type != "2") {//播放节目和播放列表
                                    jsonObject.id?.let {
                                        AppDatabase.instance.programUrlDao().delById(it)
                                        AppDatabase.instance.programJsonDao().deletByPId(it)
                                        fomatJson()
                                        ZipUtils.deleteDirectory(Common.DIRADDRESS + File.separator + it)
                                    }
                                }

                                if (jsonObject.status == "1" && jsonObject.type == "2") { //插播内容
                                    jsonObject.id?.let {
                                        AppDatabase.instance.interPlayDao().deletByPId(it)
                                        //刷新插播内容
                                        interPlayText()
                                    }
                                }
                            }
                            "1008" -> {//插播内容 文本 InterPlayBean
                                val type = object : TypeToken<ResultBean<InterPlayBean>>() {}.type
                                val data = Gson().fromJson<ResultBean<InterPlayBean>>(json, type)

                                AppDatabase.instance.interPlayDao().insert(data.data)
                                interPlayText()
                            }
                            "1009" -> {//激活
                                val type = object : TypeToken<ResultBean<ActiveTime>>() {}.type
                                val data = Gson().fromJson<ResultBean<ActiveTime>>(json, type)
                                SPUtil.putSP(Common.AUTHTIMEEND, data.data.endDate!!)
                                SPUtil.putSP(Common.AUTHTIMESTART, data.data.startDate!!)
                                SPUtil.putSP(Common.AUTH, "是")
                                //隐形未激活的窗口
                                if (dialog.isShowing) {
                                    dialog.hide()
                                }
                                returnFun("1", data.type!!)
                            }
                        }
                    }
                }

                override fun onFail(throwable: Throwable?) {
                    //  ToastUtils.s("${throwable?.message}")
                }
            })
    }

    /**
     * 设置音量计划
     */
    private fun setVolumePlan() {
        SchedulerManager.cleanTask()
        var allVolumePlan = AppDatabase.instance.volumeDao().getAllVolumePlan()
        allVolumePlan.forEach { time ->
            SchedulerManager.addSchedulervolume(
                Utils.timeToTaskStr(time.startTime!!),
                time.value!!
            )
        }
    }

    /**
     * 1008 插播内容
     */
    private fun interPlayText() {
        var all = AppDatabase.instance.interPlayDao().getAll()

        all.forEach {
            NewShowViewUtils.newTextView2(it, this, root_view)
        }
    }

    /**
     * 节目下载
     */
    private fun dowmProgramFun(data: ProgramUrlBean) {

        var ip = SPUtil.getSP(Common.IP, Common.ip)
        var web = SPUtil.getSP(Common.WEB_PORT, Common.web_port)
        var downUrl = "http://$ip:$web${Common.DOWNURL}${data.programId}"
        HttpUtil.downloadFile(
            downUrl,
            Common.DIRADDRESS,
            "${data.programId}.zip",
            object : OnDownloadListener {
                override fun onDownloadSuccess(file: File?) {
                    //下载成功  解压 解析
                    returnFun2("3", data.publishDetailId!!, "1")
                    Log.d("数据","下载成功${data.publishDetailId!!}")
                    var unzip = ZipUtils.unzip(
                        Common.DIRADDRESS + File.separator + data.programId + ".zip",
                        ZipUtils.createFile(Common.DIRADDRESS, data.programId).path
                    )

                    fixPlayJson(data, unzip)

                }

                override fun onDownloading(progress: Int) {

                }

                override fun onDownloadFailed(e: Exception?) {
                    returnFun2("3", data.publishDetailId!!, "0")
                    Log.d("数据","下载失败${data.publishDetailId!!}")
                    GlobalScope.launch(Dispatchers.Main) {
                        (viewPage.adapter as FragmentStateAdapter).notifyDataSetChanged()
                    }
                }

            })
    }

    /**
     * 解析播放json
     */

    fun fixPlayJson(data: ProgramUrlBean, unzip: Boolean) {

        if (unzip) {
            //todo 播放列表有多个json
            if (data.type == "1") { //播放列表处理
                val fixListId = Utils.fixListId(data.materialIds!!)
                fixListId.forEach {
                    val json =
                        FileUtils.getJsonFromFile(Common.DIRADDRESS + File.separator + data.programId + File.separator + it + ".json")
                    var jsonBean = ProgramJsonBean(data.programId, it, json)
                    AppDatabase.instance.programJsonDao().insert(jsonBean)
                }
            } else {
                var json =
                    FileUtils.getJsonFromFile(Common.DIRADDRESS + File.separator + data.programId + File.separator + data.programId + ".json")
                data.json = json
            }


        }


        //判断模式 追加 插播 替换
        when (data.mode) {
            "1" -> {//追加
                AppDatabase.instance.programUrlDao().insert(data)
            }
            "2" -> {//插播
                var programUrlBean = AppDatabase.instance.programUrlDao().getProgramUrlBean()
                AppDatabase.instance.programUrlDao().deletAll()
                AppDatabase.instance.programUrlDao().insert(data)
                AppDatabase.instance.programUrlDao().insertAll(programUrlBean)
            }
            "3" -> {//替换
                AppDatabase.instance.programUrlDao().deletAll()
                AppDatabase.instance.programUrlDao().insert(data)
            }
            else -> {
                AppDatabase.instance.programUrlDao().insert(data)
            }
        }

        //删除压缩包
        GlobalScope.launch {
            ZipUtils.deleteFile(Common.DIRADDRESS + File.separator + data.programId + ".zip")
        }
        //通知解析节目
        fomatJson()
    }

    /**
     * 更新方法
     */
    private fun UpDatafun(data: UpDataBean) {
        var ip = SPUtil.getSP(Common.IP, Common.ip)
        var web = SPUtil.getSP(Common.WEB_PORT, Common.web_port)
        var downUrl = "http://$ip:$web${Common.DOWNAPK}${data.id}"
        HttpUtil.downloadFile(
            downUrl,
            Common.DIRADDRESS + "/apk/",
            "${data.version}.apk",
            object : OnDownloadListener {
                override fun onDownloadSuccess(file: File?) {
                    returnFun("1", "1002")
                    SmdtManagerUtils.smdtSilentInstall(file!!.path)
                }

                override fun onDownloading(progress: Int) {

                }

                override fun onDownloadFailed(e: Exception?) {
                    returnFun("0", "1002")
                }


            })
    }

    /**
     * 返回数据
     */
    private fun returnFun(code: String, type: String) {
        login()
        val gson = Gson()
        val resultBean = ReturnObject<NullData>()
        resultBean.code = code
        resultBean.type = type
        tcpConnect(MsgUtils.stringToByte(gson.toJson(ResultJson(gson.toJson(resultBean)))))

    }

    /**
     * 发送数据
     */

    private fun SendMsg(type: String, bean: Any) {
        if (type != "5") {
            login()
        }
        val gson = Gson()
        val resultBean = SendObject()
        resultBean.type = type
        resultBean.data = bean
        tcpConnect(MsgUtils.stringToByte(gson.toJson(ResultJson(gson.toJson(resultBean)))))

    }

    private fun login() {
        var gson = Gson()
        var loginJson = gson.toJson(ResultJson(gson.toJson(loginBean())))
        tcpConnect(MsgUtils.stringToByte(loginJson))
    }

    /**
     * 节目状态返回
     * @param code String
     * @param type String
     * @param id String
     * @param staus String
     */
    private fun returnFun2(type: String, id: String, staus: String) {
        login()

        var gson = Gson()
        val resultBean = ReturnObject<PragrmStatusBean>()
        resultBean.code = null
        resultBean.type = type
        val p = PragrmStatusBean(id, staus)
        resultBean.data = p
        tcpConnect(MsgUtils.stringToByte(gson.toJson(ResultJson(gson.toJson(resultBean)))))

    }

    /**
     * 登录 返回设置
     */
    private fun setLoginSet(data: loginResult) {


        data.isActive?.let {
            //0是未激活
            if (it == "0") {
                SendMsg("5", NullData())
            }
        }


        if (TextUtils.isEmpty(data.volume).not()) {
//            SmdtManagerUtils.smdtSetAndroidVolume(data.volume.toInt())
        }
        if (TextUtils.isEmpty(data.isMute).not()) {
            if (data.isMute == "1") {
//                SmdtManagerUtils.smdtSetAndroidVolume(0)
            }
        }

        if (TextUtils.isEmpty(data.isActive).not()) {
            if (data.isActive == "1") {
//                SPUtil.putSP(Common.AUTH, "是")
            } else {
//                SPUtil.putSP(Common.AUTH, "无")
            }
        }

//        if (TextUtils.isEmpty(data.isBlacklight).not()) {
//            if (data.isBlacklight == "1") {
//                SmdtManagerUtils.smdtSetLcdBackLight(1)
//            } else {
//                SmdtManagerUtils.smdtSetLcdBackLight(0)
//            }
//        }

//        if (TextUtils.isEmpty(data.isRootStart).not()) {
//            if (data.isRootStart == "1") {
//                SPUtil.putSP(Common.REBOOT, "开")
//            } else {
//                SPUtil.putSP(Common.REBOOT, "关")
//            }
//        }
//        if (TextUtils.isEmpty(data.isGuard).not()) {
//            if (data.isGuard == "1") {
//                SPUtil.putSP(Common.PROTECT, "开")
//            } else {
//                SPUtil.putSP(Common.PROTECT, "关")
//            }
//        }
//        if (TextUtils.isEmpty(data.isStatus).not()) {
//            if (data.isStatus == "1") {
//                SmdtManagerUtils.smdtSetStatusBar(true)
//            } else {
//                SmdtManagerUtils.smdtSetStatusBar(false)
//            }
//        }

        if (TextUtils.isEmpty(data.screen).not()) {
//            SmdtManagerUtils.setScreenAngle(data.screen)
//            when (data.screen) {
//                "0" -> {
//                    SmdtManagerUtils.setRotation("0")
//                }
//                "1" -> {
//                    SmdtManagerUtils.setRotation("90")
//                }
//                "2" -> {
//                    SmdtManagerUtils.setRotation("180")
//                }
//                "3" -> {
//                    SmdtManagerUtils.setRotation("270")
//                }
//            }

        }

    }

    override fun onResume() {
        super.onResume()
        //是否连接 没有连接的话建立连接
        if (SPUtil.getSP(Common.ISCONNECT, "否") == "否") {
            if (SPUtil.getSP(Common.MOUDLE,"联机模式")=="单机模式")return
            val gson = Gson()
            val loginJson = gson.toJson(ResultJson(gson.toJson(loginBean())))
            tcpConnect(MsgUtils.stringToByte(loginJson))
        }


    }

    /**
     * 删除不用的文件
     */
    private fun delFile() {
        try {
            val file = File(Common.DIRADDRESS)
            val listFiles = file.listFiles()
            listFiles?.let { it ->
                it.forEach {
                    var byId = AppDatabase.instance.programUrlDao().getById(it.name)
                    if (TextUtils.isEmpty(byId)) {
                        ZipUtils.deleteDirectory(Common.DIRADDRESS + File.separator + it.name)
                    }
                }
            }
        } catch (e: Exception) {
            Log.d("Exception", "删除文件异常...")
        }
    }

    /**
     * 发送资源播放次数
     */
    private fun reportPlays() {
        val resPlayNumDao = AppDatabase.instance.resPlayNumDao().getProgramUrlBean()
        SendMsg("4", resPlayNumDao)

    }

    override fun onDestroy() {
        Common.LOGINGFLAG = 1
        SPUtil.putSP(Common.ISCONNECT, "否")
        SPUtil.putSP(Common.LOGIN_STATE, "未登录")
        Log.d("onDestroy", "onDestroy")
        super.onDestroy()
    }

    /**
     * 设置设备
     */
    private fun setDevices(data: SetData) {
        /**
         * 音量
         */
        if (TextUtils.isEmpty(data.volume).not()) {
            SmdtManagerUtils.smdtSetAndroidVolume(data.volume!!.toInt())
        }

        /**
         * 设置是否激活
         */
        if (TextUtils.isEmpty(data.isActive).not()) {
            if (data.isActive == "1") {
                SPUtil.putSP(Common.AUTH, "是")
            } else {
                SPUtil.putSP(Common.AUTH, "无")
            }
        }
        /**
         * 设置是否背光
         */
        if (TextUtils.isEmpty(data.isBlacklight).not()) {
            if (data.isBlacklight == "1") {
                SmdtManagerUtils.smdtSetLcdBackLight(1)
            } else {
                SmdtManagerUtils.smdtSetLcdBackLight(0)
            }
        }
        /**
         * 设置是否开机自启
         */
        if (TextUtils.isEmpty(data.isRootStart).not()) {
            if (data.isRootStart == "1") {
                SPUtil.putSP(Common.REBOOT, "开")
            } else {
                SPUtil.putSP(Common.REBOOT, "关")
            }
        }
        /**
         * 是否开启进程守护
         */
        if (TextUtils.isEmpty(data.isGuard).not()) {
            if (data.isGuard == "1") {
                SPUtil.putSP(Common.PROTECT, "开")
            } else {
                SPUtil.putSP(Common.PROTECT, "关")
            }
        }
        /**
         * 是否显示状态栏
         */
        if (TextUtils.isEmpty(data.isStatus).not()) {
            if (data.isStatus == "1") {
                SmdtManagerUtils.smdtSetStatusBar(true)
            } else {
                SmdtManagerUtils.smdtSetStatusBar(false)
            }
        }
        /**
         * 屏幕角度
         */
        if (TextUtils.isEmpty(data.screenAngle).not()) {
            setScreenonChange(data.screenAngle.toString())
//            SPUtil.putSP(Common.ANGLE, data.screenAngle.toString())
//            SmdtManagerUtils.setRotation((data.screenAngle).toString())
        }
        /**
         *
         * 屏幕方向
         */
        if (TextUtils.isEmpty(data.screen).not()) {
            /**
             * 设置屏幕方向 0 1 2 3
             */
            when (data.screen) {
                "0" -> {
                    SmdtManagerUtils.setRotation("0")
                }
                "1" -> {
                    SmdtManagerUtils.setRotation("90")
                }
                "2" -> {
                    SmdtManagerUtils.setRotation("180")
                }
                "3" -> {
                    SmdtManagerUtils.setRotation("270")
                }
            }
            SPUtil.putSP(Common.SCREEN,data.screen!!)

        }

        if (TextUtils.isEmpty(data.isRemoveShow).not()) {
            //todo 清空节目
            if (data.isRemoveShow == "1") {
                AppDatabase.instance.programUrlDao().deletAll()
                AppDatabase.instance.programJsonDao().deletAll()
                AppDatabase.instance.interPlayDao().deletAll()
                arrayList.clear()
                (viewPage.adapter as FragmentStateAdapter).notifyDataSetChanged()
                fomatJson()
                ZipUtils.deleteDirectory(Common.DIRADDRESS ,false)
            }

        }
        /**
         * 重启
         */
        if (TextUtils.isEmpty(data.isBoot).not()) {
            if (data.isBoot == "1") {
                SmdtManagerUtils.smdtReboot()
            }

        }
        /**
         * 是否关机
         */
        if (TextUtils.isEmpty(data.isshutdown).not()) {
            if (data.isshutdown == "1") {
                SmdtManagerUtils.shutDown()
            }

        }
        /**
         * 亮度
         */
        if (TextUtils.isEmpty(data.lightValue).not()) {

            SmdtManagerUtils.setBrightness(data.lightValue!!.toInt(),this)
        }

    }
    /**
     * 上传截图
     */
    fun upScreenshotsImg(id: String) {
        var hashmap = hashMapOf<String, String>()
        hashmap["programId"] = Common.programId //当前节目的Id
        hashmap["deviceId"] = SmdtManagerUtils.getAndroid_ID()
        hashmap["id"] = id
//        hashmap["deviceId"] = "6bb4b8db891a4116a85f897f953c0fba"
        var name = "Screenshot.png"
        SmdtManagerUtils.smdtTakeScreenshot(Common.DIRADDRESS, name)
        SmdtManagerUtils.execSuCmd("screencap -p " + Common.DIRADDRESS + File.separator + name)

        var ip = SPUtil.getSP(Common.IP, Common.ip)
        var web = SPUtil.getSP(Common.WEB_PORT, Common.web_port)
        var url = "http://$ip:$web${Common.UPLODURL}"
        HttpUtil.upLoadFile(
            url,
            File(Common.DIRADDRESS + File.separator + name),
            hashmap,
            object : RequestListener {
                override fun OnRequestSuccess(data: String) {
                    Log.d("截图数据 ", data)
                }

                override fun OnRequestErro(data: String) {
                    Log.d("截图数据 ", data)
                }

            })


    }

    fun senRegistMsg() {
        var registData = registData()
        registData.deviceId = SmdtManagerUtils.getAndroid_ID()
        registData.diskSpace =
            "${SmdtManagerUtils.getAvailableMemory()}/ ${SmdtManagerUtils.getInternalStorageMemory()}"
        registData.firmware = SmdtManagerUtils.getFormattedKernelVersion()
        registData.hardVersion = SmdtManagerUtils.getAndroidModel()
        registData.systemType = SmdtManagerUtils.getDeviceBrand()
        registData.softVersion = packageManager.getPackageInfo(packageName, 0).versionName
        registData.module = "1"
        registData.type = "1"
        registData.screen = SPUtil.getSP(Common.SCREEN, "2")!!
        registData.resolution =
            "${SmdtManagerUtils.smdtGetScreenWidth()} * ${SmdtManagerUtils.smdtGetScreenHeight()}"
        registData.mac = SmdtManagerUtils.smdtGetEthMacAddress()
        registData.ip = SmdtManagerUtils.smdtGetEthIPAddress()
        registData.volume = SmdtManagerUtils.getCurrentSysVolume().toString()
        registData.isMute = if (SmdtManagerUtils.getCurrentSysVolume() == 0) "1" else "0"
        registData.isActive = if (SPUtil.getSP(Common.AUTH, "无") == "无") "0" else "1"
        registData.isBlacklight = if (SmdtManagerUtils.smdtGetLcdLightStatus() == 0) "1" else "0"
        registData.isRootStart = if (SPUtil.getSP(Common.REBOOT) == "开") "1" else "0"
        registData.isGuard = if (SPUtil.getSP(Common.PROTECT) == "开") "1" else "0"
        registData.isStatus = if (SmdtManagerUtils.smdtGetStatusBar() == 1) "1" else "0"
        registData.screenAngle = SPUtil.getSP(Common.ANGLE, "0") + ""
        var registBean = RegistBean(registData, "2")

        var gson = Gson()
        var regist = gson.toJson(ResultJson(gson.toJson(registBean)))
        tcpConnect(MsgUtils.stringToByte(regist))
    }

}